using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Web.UI;

namespace Skywave.Security
{
    public static class RijndaelWeb
    {
        public static RijndaelManaged GetRijndael(System.Web.SessionState.HttpSessionState session)
        {
            RijndaelManaged r = new RijndaelManaged();
            string sessionIVkey = "RijndaelWeb_IV";
            string sessionKEYkey = "RijndaelWeb_Key";
            byte[] IV = session[sessionIVkey] as byte[];
            byte[] Key = session[sessionKEYkey] as byte[];
            //foreach (string key in session.Keys)
            //{
            //    if (key == "IV")
            //    {
            //        IV = (byte[])session["IV"];
            //    }
            //    else if (key == "Key")
            //    {
            //        Key = (byte[])session["Key"];
            //    }
            //}
            if (IV == null || Key == null)
            {
                session.Add(sessionIVkey, r.IV);
                session.Add(sessionKEYkey, r.Key);
            }
            else
            {
                r.IV = IV;
                r.Key = Key;
            }
            return r;
        }

        public static string Encrypt(System.Web.SessionState.HttpSessionState session, string input)
        {
            byte[] inputBuffer, outputBuffer;
            RijndaelManaged RMCrypto = GetRijndael(session);
            inputBuffer = Encoding.Unicode.GetBytes(input);
            outputBuffer = RMCrypto.CreateEncryptor().TransformFinalBlock(inputBuffer, 0, inputBuffer.Length);
            string r = ComponentModel.ByteArrayConverter.ToString(outputBuffer);
            return r;
        }
        public static string Encrypt(Page page, string input)
        {
            return Encrypt(page.Session, input);
        }

        public static string Decrypt(System.Web.SessionState.HttpSessionState session, string input)
        {
            byte[] inputBuffer, outputBuffer;
            RijndaelManaged RMCrypto = GetRijndael(session);
            inputBuffer = ComponentModel.ByteArrayConverter.FromString(input);
            outputBuffer = RMCrypto.CreateDecryptor().TransformFinalBlock(inputBuffer, 0, inputBuffer.Length);
            string r = Encoding.Unicode.GetString(outputBuffer);
            return r;
        }
        public static string Decrypt(Page page, string input)
        {
            return Decrypt(page.Session, input);
        }
    }
}
